package com.demo.main.dao.impl;

import com.demo.main.dao.BookDao;
import com.demo.main.entity.Book;
import com.demo.main.utils.JDBCUtil;
import com.demo.main.vo.BookVo;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// 定义BookDaoImpl类，它继承自BaseDaoImpl类并实现了BookDao接口
public class BookDaoImpl extends BaseDaoImpl<Book, Integer> implements BookDao {
    // 定义用于查询书籍详细信息的SQL语句
    private final String bookVoSql = "select book_id, title, author, publisher, publish_date, isbn, classification_number, book.category_id as category_id, total_copies, available_copies, category_name from book, book_category WHERE book.category_id = book_category.category_id";

    // 构造方法，调用父类的构造方法初始化一些基础信息
    public BookDaoImpl() {
        super("book", "book_id", Book.class);
    }
    // 定义一个私有方法，用于构建查询条件
    private static Map<String, Object> buildConditions(String title, String author, String isbn, String bookCategoryName) {
        Map<String, Object> conditions = new HashMap<>();
        // 使用LIKE操作符构建模糊查询条件
        conditions.put("title", Collections.singletonMap(title, JDBCUtil.Operator.LIKE));
        conditions.put("author", Collections.singletonMap(author, JDBCUtil.Operator.LIKE));
        // 直接添加ISBN和类别名称作为查询条件
        conditions.put("isbn", isbn);
        conditions.put("category_name", bookCategoryName);
        return conditions;
    }
    // 重写selectAllBookVo方法，用于分页查询所有书籍的详细信息
    @Override
    public List<BookVo> selectAllBookVo(int pageNum) {
        return selectAllWithDetailsDesc(bookVoSql, "book.book_id", BookVo.class, pageNum);
    }
    // 重写selectBookVoByCondition方法，用于根据条件分页查询书籍的详细信息
    @Override
    public List<BookVo> selectBookVoByCondition(String title, String author, String isbn, String bookCategoryName, int pageNum) {
        Map<String, Object> conditions = buildConditions(title, author, isbn, bookCategoryName);
        return selectByConditionWithDetailsDesc(bookVoSql, conditions, BookVo.class, pageNum);
    }
    // 重写selectBookVoCountByCondition方法，用于根据条件统计书籍的数量
    @Override
    public int selectBookVoCountByCondition(String title, String author, String isbn, String bookCategoryName) {
        Map<String, Object> conditions = buildConditions(title, author, isbn, bookCategoryName);
        return selectCountByConditionWithDetails(bookVoSql, conditions);
    }
    // 重写borrowBook方法，用于调用存储过程借书，默认借阅时间为30天（已在存储过程中定义）
    @Override
    public JDBCUtil.StoredProcedureResult borrowBook(int userId, int bookId, int borrowDays) throws SQLException {
        return callStoredProcedure("borrow_book", userId, bookId, borrowDays);
    }
    // 重写returnBook方法，用于调用存储过程还书
    @Override
    public JDBCUtil.StoredProcedureResult returnBook(int userId, int bookId) throws SQLException {
        return callStoredProcedure("return_book", userId, bookId);
    }
}